package org.example.mynote.service.Impl;

import org.example.mynote.Entity.User;
import org.example.mynote.dto.LoginResponseDTO;
import org.example.mynote.mapper.UserMapper;
import org.example.mynote.service.UserService;
import org.example.mynote.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User register(String username, String password) {
        if (userMapper.findByUsername(username) != null) {
            throw new RuntimeException("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(passwordEncoder.encode(password));

        // 调用 Mapper 的 save 方法
        userMapper.save(user);

        // 因为我们在 XML 中配置了 keyProperty="id"，
        // 执行完 userMapper.save(user) 后，这个 user 对象的 id 已经被回填了！
        return user;
    }

    @Override
    public LoginResponseDTO login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (passwordEncoder.matches(password, user.getPasswordHash())) {
            // 密码正确，生成 Token
            String token = jwtUtil.generateToken(username);

            // 构建并返回一个完整的 LoginResponse 对象
            return new LoginResponseDTO(token, user.getId(), user.getUsername());
        } else {
            // 密码错误
            throw new RuntimeException("密码错误");
        }
    }


    // 登录逻辑稍后实现
}
